<template>
  <a-dropdown
      :trigger="['click']"
      v-model="show"
      :overlayStyle="{ maxHeight: '70vh', overflow: 'hidden' }"
  >
    <div slot="overlay">
      <a-spin :spinning="loading">
        <a-tabs
            class="dropdown-tabs"
            :tabBarStyle="{textAlign: 'center'}"
            :style="{width: '297px'}"
        >
          <a-tab-pane tab="未读消息" key="1">
            <a-list
                class="tab-pane"
                :data-source="noReadDataSource"
                :pagination="{
                current: noReadPageParams.page,
                pageSize: noReadPageParams.pageSize,
                total: noReadPageParams.total,
                onChange: noReadHandlePageChange,
                simple: true
              }"
            >
              <a-list-item
                  slot="renderItem"
                  slot-scope="item"
                  class="message-item"
              >
                <template #actions>
                  <a @click.stop="read(item)">标为已读</a>
                </template>
                <a-list-item-meta>
                  <span slot="description" class="message-description">{{ item.description }}</span>
                  <a slot="title" class="message-title">{{ item.title }}</a>
                  <a-avatar
                      slot="avatar"
                      :src="require('@/assets/img/kISTdvpyTAhtGxpovNWd.png')"
                  />
                </a-list-item-meta>
              </a-list-item>
            </a-list>
          </a-tab-pane>
          <a-tab-pane tab="已读消息" key="2">
            <a-list
                class="tab-pane"
                :data-source="readDataSource"
                :pagination="{
                current: readPageParams.page,
                pageSize: readPageParams.pageSize,
                total: readPageParams.total,
                onChange: readHandlePageChange,
                simple: true
              }"
            >
              <a-list-item
                  slot="renderItem"
                  slot-scope="item"
                  class="message-item"
              >
                <a-list-item-meta>
                  <span slot="description" class="message-description">{{ item.description }}</span>
                  <a slot="title" class="message-title">{{ item.title }}</a>
                  <a-avatar
                      slot="avatar"
                      :src="require('@/assets/img/ThXAXghbEsBCCSDihZxY.png')"
                  />
                </a-list-item-meta>
              </a-list-item>
            </a-list>
          </a-tab-pane>
        </a-tabs>
      </a-spin>
    </div>
    <span @click="fetchData" class="header-notice">
      <a-badge class="notice-badge" :count="count">
        <a-icon :class="['header-notice-icon']" type="bell"/>
      </a-badge>
    </span>
  </a-dropdown>
</template>

<script>
import { page, read } from '@/services/notice'
import { mapGetters } from "vuex";
import debounce from 'lodash/debounce'

export default {
  name: 'HeaderNotice',
  data() {
    return {
      loading: false,
      show: false,
      readPageParams: {
        page: 1,
        pageSize: 5,
        total: 0,
      },
      noReadPageParams: {
        page: 1,
        pageSize: 5,
        total: 0,
      },
      count: 0,
      readDataSource: [],
      noReadDataSource: [],
    }
  },
  computed: {
    ...mapGetters('account', ['user']),
  },
  created() {
    this.fetchData()
    this.debouncedFetchData = debounce(this.fetchData, 300)
  },
  mounted() {
    this.handleWebsocketMessage = (event) => {
      this.listenMsg(event.detail)
    }
    window.addEventListener('websocket-message', this.handleWebsocketMessage)
  },
  beforeDestroy() {
    window.removeEventListener('websocket-message', this.handleWebsocketMessage)
    this.debouncedFetchData.cancel()
  },
  methods: {
    listenMsg(msg) {
      console.log('收到WebSocket消息:', msg)
      this.debouncedFetchData()
    },
    readHandlePageChange(page, pageSize) {
      this.readPageParams.page = page
      this.readPageParams.pageSize = pageSize
      this.fetchData()
    },
    noReadHandlePageChange(page, pageSize) {
      this.noReadPageParams.page = page
      this.noReadPageParams.pageSize = pageSize
      this.fetchData()
    },
    async fetchData() {
      if (this.loading) return
      this.loading = true
      try {
        const [readRes, unreadRes] = await Promise.all([
          page({
            page: this.readPageParams.page,
            pageSize: this.readPageParams.pageSize,
            status: "已读",
            userId: this.user.id
          }),
          page({
            page: this.noReadPageParams.page,
            pageSize: this.noReadPageParams.pageSize,
            status: "未读",
            userId: this.user.id
          })
        ])

        this.readDataSource = readRes?.data?.data?.listData || []
        this.readPageParams.total = readRes?.data?.data?.total || 0
        this.readPageParams.pageSize = readRes?.data?.data?.pageSize || 5
        this.readPageParams.page = readRes?.data?.page || 1

        this.noReadDataSource = unreadRes?.data?.data?.listData || []
        this.noReadPageParams.total = unreadRes?.data?.data?.total || 0
        this.noReadPageParams.pageSize = unreadRes?.data?.data?.pageSize || 5
        this.noReadPageParams.page = unreadRes?.data?.page || 1
        this.count = unreadRes?.data?.data?.total || 0
      } catch (error) {
        console.error('获取消息失败:', error)
        this.$message.error('获取消息失败')
      } finally {
        this.loading = false
      }
    },
    async read(record) {
      try {
        const res = await read(record.id)
        if (res?.data?.code === 200) {
          this.$message.success("操作成功!")
          this.$router.go(0);
        }
      } catch (error) {
        console.error('标记已读失败:', error)
        this.$message.error('操作失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.header-notice {
  display: inline-block;
  transition: all 0.3s;
  cursor: pointer;

  span {
    vertical-align: initial;
  }

  .notice-badge {
    color: inherit;

    .header-notice-icon {
      font-size: 16px;
      padding: 4px;
    }
  }
}

.dropdown-tabs {
  background-color: #fff;
  box-shadow:
      0 1px 2px rgba(0,0,0,0.05),
      0 8px 24px rgba(0,0,0,0.1);
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  position: relative;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(to right, #1890ff, #52c41a);
    border-radius: 8px 8px 0 0;
  }

  /deep/ .ant-tabs-tab {
    padding: 12px 16px;
    &-active {
      color: #1890ff;
      font-weight: 500;
    }
  }

  .tab-pane {
    position: relative;
    padding: 0 12px 56px;
    min-height: 250px;
    max-height: 60vh;
    overflow-y: auto;

    /deep/ .ant-pagination {
      position: absolute;
      bottom: 12px;
      left: 0;
      right: 0;
      padding: 8px 12px;
      background: #fff;
      border-top: 1px solid #f0f0f0;
      margin: 0;
    }

    .message-item {
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .message-title {
        display: block;
        white-space: normal;
        word-break: break-word;
        font-weight: 500;
        margin-bottom: 4px;
        color: rgba(0, 0, 0, 0.85);
      }

      .message-description {
        display: block;
        white-space: normal;
        word-break: break-word;
        color: rgba(0, 0, 0, 0.65);
      }
    }

    /deep/ .ant-list-item-meta {
      align-items: center;

      .ant-list-item-meta-content {
        flex: 1;
        min-width: 0;

        .ant-list-item-meta-title {
          margin-bottom: 4px;
          white-space: normal;
          word-break: break-word;
        }

        .ant-list-item-meta-description {
          white-space: normal;
          word-break: break-word;
        }
      }
    }
  }
}
</style>